<template>
  <div>
    <!-- <el-tabs v-model="activeTab" @tab-click="changeTab">
      <el-tab-pane label="入站规则" name="ruleFrom"></el-tab-pane>
      <el-tab-pane label="出站规则" name="ruleTo"></el-tab-pane>
    </el-tabs> -->
    <HETTable1
        ref="portRulesTable"
        :tableData="data.tableData"
        :tHead="data.tHead"
        :headerOperation="!treeStore.isShowStrategyDetail ? data.headerOperation : []"
        :checkBox="treeStore.isShowStrategyDetail ? false : true"
        :total="data.total"
        @chooseData="chooseData"
        @getTableData="getPortRuleList"
    >
      <template #from_to>
        <el-table-column label="规则类型">
          <template #default="scope">
            {{ scope.row.from_to == 1 ? "入站规则" : "出站规则" }}
          </template>
        </el-table-column>
      </template>
      <template #protocal>
        <el-table-column label="协议">
          <template #default="scope">
            {{ scope.row.protocal == 1 ? "TCP" : "UDP" }}
          </template>
        </el-table-column>
      </template>
      <template #localAddr>
        <el-table-column label="本地地址" v-if="activeTab == 'ruleFrom'">
          <template #default="scope">
            {{ scope.row.localAddr }}
          </template>
        </el-table-column>
      </template>
      <template #localPort>
        <el-table-column label="本地端口" v-if="activeTab == 'ruleFrom'">
          <template #default="scope">
            {{ scope.row.localPort }}
          </template>
        </el-table-column>
      </template>
      <template #remoteAddr>
        <el-table-column label="远端地址" v-if="activeTab == 'ruleTo'">
          <template #default="scope">
            {{ scope.row.remoteAddr }}
          </template>
        </el-table-column>
      </template>
      <template #remotePort>
        <el-table-column label="远端端口" v-if="activeTab == 'ruleTo'">
          <template #default="scope">
            {{ scope.row.remotePort }}
          </template>
        </el-table-column>
      </template>
      <template #enable>
        <el-table-column label="启用">
          <template #default="scope">
            <el-switch
                v-model="scope.row.enable"
                :active-value="1"
                :inactive-value="0"
                :loading="loading"
                :disabled="treeStore.isShowStrategyDetail"
                @change="changeEnable(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
      </template>
      <template #operation>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="setPortRule(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </template>
    </HETTable1>
    <el-dialog
        :title="dialogTitle"
        :model-value="dialogAsync"
        :center="true"
        width="35%"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        @close="cancel()"
    >
      <div class="dialog-body">
        <el-form ref="formRef" status-icon :model="form" :rules="rules" label-width="120px">
          <el-form-item label="规则类型" prop="fromTo">
            <el-radio-group v-model="form.fromTo" disabled="true">
              <el-radio :value="1">入站规则</el-radio>
              <el-radio :value="2">出站规则</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="规则名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入规则名称"> </el-input>
          </el-form-item>
          <el-form-item label="通信协议" prop="protocal">
            <el-radio-group v-model="form.protocal">
              <el-radio :value="1">TCP</el-radio>
              <el-radio :value="2">UDP</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="form.fromTo == 1">
            <el-form-item label="本地地址" prop="localAddr">
              <el-input v-model="form.localAddr" placeholder="请输入本地地址"> </el-input>
            </el-form-item>
            <el-form-item label="本地端口" prop="localPort">
              <el-input v-model="form.localPort" placeholder="请输入本地端口"> </el-input>
            </el-form-item>
          </div>
          <div v-else>
            <el-form-item label="远端地址" prop="remoteAddr">
              <el-input v-model="form.remoteAddr" placeholder="请输入远端地址">
              </el-input>
            </el-form-item>
            <el-form-item label="远端端口" prop="remotePort">
              <el-input v-model="form.remotePort" placeholder="请输入远端端口">
              </el-input>
            </el-form-item>
          </div>
          <el-form-item label="是否启用" prop="enable">
            <el-switch v-model="form.enable" :active-value="1" :inactive-value="0">
            </el-switch>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="submitForm(formRef)" type="primary">确定</el-button>
        <el-button @click="cancel()"> 取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, markRaw} from "vue";
import {useTreeStore} from "~/utils/pinia/tree.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {Search, Refresh, Delete, Plus} from "@element-plus/icons-vue";
import {validPort, validIp} from "~/utils/common/validation.js";
import {
  req_getPortRulesLinux,
  req_addPortRuleLinux,
  req_delPortRulesLinux,
  req_setPortRulesLinux,
  req_scanPortRulesLinux,
} from "~/utils/axios/index.js";
import {eventBus} from "~/utils/common/eventBus.js";

eventBus.on("getStrategyDetail", (detail) => {
  data.tableData = detail.data;
  data.total = detail.total;
});
const treeStore = useTreeStore();
const portRulesTable = ref();
const formRef = ref();
treeStore.treeLinkedTableRef = portRulesTable;
const dialogAsync = ref(false);
const dialogTitle = ref("新建端口规则");
// const activeTab = ref();
// const changeTab = (tab) => {
//   activeTab.value = tab.props.name;
// };
const form = ref({
  fromTo: 2,
  name: "",
  protocal: 1,
  localAddr: "",
  localPort: null,
  remoteAddr: "",
  remotePort: null,
  enable: 0,
});

const rules = ref({
  name: [{required: true, message: "规则名称不能为空", trigger: "blur"}],
  localAddr: [
    {required: true, message: "本地地址不能为空", trigger: "blur"},
    {validator: validIp, trigger: "blur"},
  ],
  localPort: [
    {required: true, message: "本地端口不能为空", trigger: "blur"},
    {validator: validPort, trigger: "blur"},
  ],
  remoteAddr: [
    {required: true, message: "远端地址不能为空", trigger: "blur"},
    {validator: validIp, trigger: "blur"},
  ],
  remotePort: [
    {required: true, message: "远端端口不能为空", trigger: "blur"},
    {validator: validPort, trigger: "blur"},
  ],
});

const scanRules = () => {
  req_scanPortRulesLinux(treeStore.treeDeviceId).then((res) => {
    res.data.succeed ? ElMessage.success("添加成功") : ElMessage.error("添加失败");
    portRulesTable.value.getTableData();
  });
};
const addNewRule = () => {
  dialogAsync.value = true;
  dialogTitle.value = "新建端口规则";
  form.value = {
    fromTo: 2,
    name: "",
    protocal: 1,
    localAddr: "",
    localPort: null,
    remoteAddr: "",
    remotePort: null,
    enable: 0,
  };
};
const delPortRules = () => {
  let params = data.selectData.map((item) => {
    return {
      id: item.id,
    };
  });
  ElMessageBox.confirm("确定要删除选中的规则？", "删除端口规则", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    center: true,
    closeOnClickModal: false,
  }).then(() => {
    req_delPortRulesLinux(treeStore.treeDeviceId, params).then((res) => {
      res.data.succeed ? ElMessage.success("删除成功") : ElMessage.error("删除失败");
      portRulesTable.value.getTableData();
    });
  });
};
const setPortRule = (rowData) => {
  dialogAsync.value = true;
  dialogTitle.value = "编辑端口规则";
  form.value = rowData;
};
// 关闭dialog
const cancel = () => {
  dialogAsync.value = false;
};
const data = reactive({
  tHead: [
    {
      label: "名称",
      prop: "name",
      isCustom: false,
    },
    {
      label: "协议",
      prop: "protocal",
      isCustom: true,
      slotName: "protocal",
    },
    {
      label: "远端地址",
      prop: "remoteAddr",
      isCustom: false,
      slotName: "remoteAddr",
    },
    {
      label: "远端端口",
      prop: "remotePort",
      isCustom: false,
      slotName: "remotePort",
    },
    {
      label: "授信",
      isCustom: true,
      slotName: "enable",
    },
    {
      label: "操作",
      isCustom: true,
      slotName: "operation",
    },
  ],
  tableData: [],
  headerOperation: [
    {
      name: "扫描",
      icon: markRaw(Plus),
      handleClick: scanRules,
    },
    {
      name: "新建规则",
      icon: markRaw(Plus),
      handleClick: addNewRule,
    },
    {
      name: "删除",
      icon: markRaw(Delete),
      handleClick: delPortRules,
    },
  ],
  selectData: [],
  total: null, // 数据总条数
});
// 多选
const chooseData = (selectData) => {
  data.selectData = selectData;
};
const loading = ref(false);
const changeEnable = (row) => {
  loading.value = true;
  req_setPortRulesLinux(treeStore.treeDeviceId, row)
      .then((res) => {
        loading.value = false;
        res.data.succeed ? ElMessage.success("操作成功") : ElMessage.error("操作失败");
        portRulesTable.value.getTableData();
      })
      .catch((err) => {
        loading.value = false;
      });
};

const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let promise;
      let msg;
      if (dialogTitle.value == "新建端口规则") {
        promise = req_addPortRuleLinux(treeStore.treeDeviceId, form.value);
        msg = "新建";
      } else {
        promise = req_setPortRulesLinux(treeStore.treeDeviceId, form.value);
        msg = "编辑";
      }
      promise.then((res) => {
        res.data.succeed
            ? ElMessage.success(msg + "成功")
            : ElMessage.error(msg + "失败");
        dialogAsync.value = false;
        portRulesTable.value.getTableData();
      });
    }
  });
};
const getPortRuleList = async (initTableParams, $filter) => {
  if (!treeStore.treeDeviceId) return;
  portRulesTable.value.loading(); // 表格加载开始
  initTableParams = {
    ...initTableParams,
    deviceId: treeStore.treeDeviceId,
    from_to: 2,
  };
  try {
    const {data: res} = await req_getPortRulesLinux(
        treeStore.treeDeviceId,
        initTableParams
    );
    portRulesTable.value.finish(); // 表格加载完成
    loading.value = false; // 停止开关的加载状态
    data.tableData = res.data || [];
    data.total = res.total || 0;
    data.selectData = [];
  } catch (err) {
    portRulesTable.value.finish(); // 表格加载完成
    loading.value = false; // 停止开关的加载状态
  }
};
</script>

<style lang="scss" scoped></style>
